package com.simple.system.service.impl;

import com.simple.common.exception.ServiceException;
import com.simple.framework.config.FileConfig;
import com.simple.framework.core.auth.JwtContext;
import com.simple.framework.core.domain.entity.SysFile;
import com.simple.framework.enums.FileStorage;
import com.simple.framework.mapper.SysFileMapper;
import com.simple.system.service.SysFileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;


/**
 * @Description 文件(SysFile)表实 服务接口实现类
 * @Author xiaoke
 * @Date 2024/8/10 18:00
 * @Version 1.0
 */
@Service
public class SysFileServiceImpl implements SysFileService {

    private final SysFileMapper sysFileMapper;

    private final FileConfig fileConfig;


    public SysFileServiceImpl(SysFileMapper sysFileMapper, FileConfig fileConfig) {
        this.sysFileMapper = sysFileMapper;
        this.fileConfig = fileConfig;
    }


    @Override
    public SysFile uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new ServiceException("文件不能为空");
        }
        try {
            // 获取当前日期并以"年-月-日"
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String dateStr = currentDate.format(formatter);

            // 创建以日期命名的目录（如果不存在）
            Path directory = Paths.get(fileConfig.getBasePath(), dateStr);
            Files.createDirectories(directory);

            // 生成随机文件名
            String originalFileName = file.getOriginalFilename();
            assert originalFileName != null;
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + fileExtension;

            // 将文件保存到指定目录下
            Path filePath = directory.resolve(fileName);
            file.transferTo(filePath.toFile());
            // 保存文件信息到数据库
            SysFile sysFile = new SysFile();
            sysFile.setStorage(FileStorage.LOCALHOST.getName());
            sysFile.setFileName(fileName);
            sysFile.setFileSize((file.getSize() / 1024.0));
            sysFile.setFileUrl(dateStr + "\\" + fileName);
            sysFile.setFileType(file.getContentType());
            sysFile.setFileSuffix(fileExtension);
            sysFile.setCreatorId(JwtContext.getUserId());
            sysFileMapper.insert(sysFile);
            return sysFile;
        } catch (IOException e) {
            throw new ServiceException("文件上传失败", 400);
        }
    }
}
